// +----------------------------------------------------------------------
// | tools 封装
// +----------------------------------------------------------------------

layui.define(['layer', 'jquery', 'upload', 'tableSelect'], function (exports, tableSelect) {

    var $ = layui.jquery,
        upload = layui.upload,
        tableSelect = layui.tableSelect,
        layer = layui.layer;
    var admin = {
        image: function (data, option) {
            var option = data.LAY_COL || {};
            option.imageWidth = option.imageWidth || 200;
            option.imageHeight = option.imageHeight || 40;
            option.imageSplit = option.imageSplit || '|';
            option.imageJoin = option.imageJoin || '<br>';
            option.title = option.title || option.field;
            var field = option.field,
                title = data[option.title];
            try {
                var value = admin.table.defaultValue(data);
            } catch (e) {
                var value = undefined;
            }
            if (value === undefined || value === null) {
                return '<img style="max-width: ' + option.imageWidth + 'px; max-height: ' + option.imageHeight + 'px;" src="' + value + '" data-image="' + title + '">';
            } else {
                var values = value.split(option.imageSplit),
                    valuesHtml = [];
                values.forEach((value, index) => {
                    valuesHtml.push('<img style="max-width: ' + option.imageWidth + 'px; max-height: ' + option.imageHeight + 'px;" src="' + value + '" data-image="' + title + '">');
                });
                return valuesHtml.join(option.imageJoin);
            }
        },
    }

    var obj = {
        // ajax 请求
        ajax: function (url, type = 'get', data = {}, suc_callback, err_callback = () => {}) {
            var load_index = layer.load();
            $.ajax({
                url: url,
                type: type,
                dataType: 'json',
                data: data,
                success: function (res) {
                    layer.close(load_index);
                    if (res.code === 0) {
                        layer.msg(res.msg, {shade: 0.3, icon: 1, time: 1000}, () => {
                            return suc_callback(res)
                        })
                    } else {
                        layer.msg(res.msg ?? '网络错误', {shade: 0.3, icon: 2, time: 1500}, () => {
                            return suc_callback(res)
                        })
                    }
                },
                error: function (res) {
                    layer.close(load_index);

                    layer.msg(res.responseJSON.message, {shade: 0.3, icon: 2, time: 2000}, () => {
                        if (res.status === 419) {
                            location.reload();
                        }
                        return err_callback(res)
                    });
                }
            });
        },
        ajaxNormal: function (url, type = 'get', data = {}, suc_callback, err_callback = () => {}) {
            $.ajax({
                url: url,
                type: type,
                dataType: 'json',
                data: data,
                success: function (res){
                    return suc_callback(res)
                },
                error:function (res){
                    return err_callback(res)
                }
            });
        },
        wangEditor: function () {
            let editorList = document.querySelectorAll(".editor");
            var wangEditor = window.wangEditor;
            if (editorList.length > 0) {
                let wangEditors = {}
                $.each(editorList, function (i, v) {
                    var wangEditorName = "wangEditor_" + i
                    wangEditors[wangEditorName] = wangEditor.createEditor({
                        selector: '#editor_' + $(this).attr('name'),
                        html: $(this).text(),
                        config: {
                            MENU_CONF: {
                                uploadImage: {
                                    server: '/admin/ajax/upload',
                                    fieldName: 'file',
                                    meta: {
                                        _token: window.CONFIG.CSRF_TOKEN,
                                        editor: 'editor',
                                    },
                                    async customInsert(res, insertFn) {
                                        let code = res.code
                                        if (code !== 0) {
                                            layer.msg(res.msg || '上传失败', {icon: 2});
                                            return
                                        }
                                        let url = res.data?.url || ''
                                        let alt = ''
                                        let href = ''
                                        insertFn(url, alt, href)
                                    }
                                }
                            },
                        }
                    })
                    let editor = wangEditors.wangEditor_0
                    window[wangEditorName] = wangEditors[wangEditorName]
                    wangEditor.createToolbar({
                        editor,
                        selector: '#editor_toolbar_' + $(this).attr("name"),
                        config: {}
                    })
                })
            }
        },
        image: function (data, option) {
            var option = data.LAY_COL || {};
            option.imageWidth = option.imageWidth || 200;
            option.imageHeight = option.imageHeight || 40;
            option.imageSplit = option.imageSplit || '|';
            option.imageJoin = option.imageJoin || '<br>';
            option.title = option.title || option.field;
            var field = option.field,
                title = data[option.title];
            try {
                var value = eval("data." + field);
            } catch (e) {
                var value = undefined;
            }
            if (value === undefined || value === null) {
                return '<img style="max-width: ' + option.imageWidth + 'px; max-height: ' + option.imageHeight + 'px;" src="' + value + '" data-image="' + title + '">';
            } else {
                var values = value.split(option.imageSplit),
                    valuesHtml = [];
                values.forEach((value, index) => {
                    valuesHtml.push('<img style="max-width: ' + option.imageWidth + 'px; max-height: ' + option.imageHeight + 'px;" src="' + value + '" data-image="' + title + '">');
                });
                return valuesHtml.join(option.imageJoin);
            }
        },
        upload: function () {
            var uploadList = document.querySelectorAll("[data-upload]");
            var uploadSelectList = document.querySelectorAll("[data-upload-select]");

            if (uploadList.length > 0) {
                $.each(uploadList, function (i, v) {
                    var uploadExts = $(this).attr('data-upload-exts') || 'doc|gif|ico|icon|jpg|mp3|mp4|p12|pem|png|rar',
                        uploadName = $(this).attr('data-upload'),
                        uploadNumber = $(this).attr('data-upload-number') || 'one',
                        uploadSign = $(this).attr('data-upload-sign') || '|',
                        uploadAccept = $(this).attr('data-upload-accept') || 'file',
                        uploadAcceptMime = $(this).attr('data-upload-mimetype') || '',
                        elem = "input[name='" + uploadName + "']",
                        uploadElem = this;

                    // 监听上传事件
                    upload.render({
                        elem: this,
                        url: '/admin/ajax/upload',
                        exts: uploadExts,
                        accept: uploadAccept,//指定允许上传时校验的文件类型
                        acceptMime: uploadAcceptMime,//规定打开文件选择框时，筛选出的文件类型
                        multiple: uploadNumber !== 'one',//是否多文件上传
                        headers: {'X-CSRF-TOKEN': window.CONFIG.CSRF_TOKEN},
                        // before: function () {
                        //     this.headers['X-CSRF-TOKEN'] = window.CONFIG.CSRF_TOKEN
                        // },
                        done: function (res) {
                            if (res.code === 0) {
                                var url = res.data.url;
                                if (uploadNumber !== 'one') {
                                    var oldUrl = $(elem).val();
                                    if (oldUrl !== '') {
                                        url = oldUrl + uploadSign + url;
                                    }
                                }
                                $(elem).val(url);
                                $(elem).trigger("input");
                                layer.msg(res.msg, {shade: 0.3, icon: 1, time: 1000})
                            } else {
                                layer.msg(res.msg ?? '网络错误', {shade: 0.3, icon: 2, time: 1500})
                            }
                            // let token = res ? res.__token__ : ''
                            // init.csrf_token = token
                            return false;
                        }
                    });

                    // 监听上传input值变化
                    $(elem).bind("input propertychange", function (event) {
                        var urlString = $(this).val(),
                            urlArray = urlString.split(uploadSign),
                            uploadIcon = $(uploadElem).attr('data-upload-icon') || "file";

                        $('#bing-' + uploadName).remove();
                        if (urlString.length > 0) {
                            var parant = $(this).parent('div');
                            var liHtml = '';
                            $.each(urlArray, function (i, v) {
                                liHtml += '<li><a><img src="' + v + '" data-image  onerror="this.src=\'/static/img/image.png\';this.onerror=null"></a><small class="uploads-delete-tip bg-red badge" data-upload-delete="' + uploadName + '" data-upload-url="' + v + '" data-upload-sign="' + uploadSign + '">×</small></li>\n';
                            });
                            parant.after('<ul id="bing-' + uploadName + '" class="layui-input-block layuimini-upload-show">\n' + liHtml + '</ul>');
                        }

                    });

                    // 非空初始化图片显示
                    if ($(elem).val() !== '') {
                        $(elem).trigger("input");
                    }
                });

                // 监听上传文件的删除事件
                $('body').on('click', '[data-upload-delete]', function () {
                    var uploadName = $(this).attr('data-upload-delete'),
                        deleteUrl = $(this).attr('data-upload-url'),
                        sign = $(this).attr('data-upload-sign');
                    var confirm = layer.confirm('确定删除？', function (index) {
                        var elem = "input[name='" + uploadName + "']";
                        var currentUrl = $(elem).val();
                        var url = '';
                        if (currentUrl !== deleteUrl) {
                            url = currentUrl.search(deleteUrl) === 0 ? currentUrl.replace(deleteUrl + sign, '') : currentUrl.replace(sign + deleteUrl, '');
                            $(elem).val(url);
                            $(elem).trigger("input");
                        } else {
                            $(elem).val(url);
                            $('#bing-' + uploadName).remove();
                        }
                        layer.close(index);
                    });
                    return false;
                });
            }

            if (uploadSelectList.length > 0) {
                $.each(uploadSelectList, function (i, v) {
                    var uploadName = $(this).attr('data-upload-select'),
                        uploadNumber = $(this).attr('data-upload-number') || 'one',
                        uploadSign = $(this).attr('data-upload-sign') || '|';

                    var selectCheck = uploadNumber === 'one' ? 'radio' : 'checkbox';
                    var elem = "input[name='" + uploadName + "']",
                        uploadElem = $(this).attr('id');

                    tableSelect.render({
                        elem: "#" + uploadElem,
                        checkedKey: 'id',
                        searchType: 'more',
                        searchList: [
                            {searchKey: 'title', searchPlaceholder: '请输入文件名'},
                        ],
                        table: {
                            url: '/admin/ajax/getUploadFiles',
                            cols: [[
                                {type: selectCheck},
                                {field: 'id', title: 'ID'},
                                {field: 'url', minWidth: 80, search: false, title: '图片信息', imageHeight: 40, align: "center", templet: obj.image},
                                {field: 'original_name', width: 150, title: '文件原名', align: "center"},
                                {field: 'mime_type', width: 120, title: 'mime类型', align: "center"},
                                {field: 'create_time', width: 200, title: '创建时间', align: "center", search: 'range'},
                            ]]
                        },
                        done: function (e, data) {
                            var urlArray = [];
                            $.each(data.data, function (index, val) {
                                urlArray.push(val.url)
                            });
                            var url = urlArray.join(uploadSign);
                            layer.msg('选择成功', {shade: 0.3, icon: 1, time: 1000}, function () {
                                $(elem).val(url);
                                $(elem).trigger("input");
                            })
                        }
                    })

                });

            }
        },
        listens: function () {
            $('body').on('click', '[data-image]', function () {
                var title = $(this).attr('data-image'),
                    src = $(this).attr('src'),
                    alt = $(this).attr('alt');
                var photos = {
                    "title": title,
                    "id": Math.random(),
                    "data": [
                        {
                            "alt": alt,
                            "pid": Math.random(),
                            "src": src,
                            "thumb": src
                        }
                    ]
                };
                parent.layer.photos({
                    photos: photos,
                    anim: 5
                });
                return false;
            });
        },
        init: function () {
            obj.listens();
            obj.upload();
            obj.wangEditor();
        }
    };

    obj.init();

    // 输出接口
    exports('tools', obj);
});
